# recommendation_pool/views.py
from django.http import JsonResponse
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
from rest_framework import status
from management.updater import DataUpdater
from problems.serializers import ProblemSerializer
from recommendation_pool.models import RecommendationStateMachine, UserRecommendationPool, RecommendationPoolQueue
from problems.models import Problem
from recommendation_history.models import RecommendationHistory
from recommendation_pool.models import UserUndoPool
from django.utils import timezone
from rest_framework_simplejwt.authentication import JWTAuthentication

from recommendation.models import SolvedProblem
from django.db.transaction import on_commit
import threading
from rest_framework.response import Response

from utils.logging_utils import log_request_response


# state_machine相关函数已废弃
@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def get_recommendation_problem_of_state_machine(request):
    try:
        state_machine = RecommendationStateMachine.objects.get(user=request.user)
        problem = state_machine.get_problem_and_switch()
        if problem is not None:
            return JsonResponse({'problem_number': problem.problem_number, 'problem_name': problem.problem_name})
        else:
            return JsonResponse({'message': 'No problem available or waiting for update'}, status=404)
    except RecommendationStateMachine.DoesNotExist:
        return JsonResponse({'error': 'No recommendation state available for this user'}, status=404)


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def handle_problem_response_of_state_machine(request):
    user_id = request.user.id  # 获取已认证用户的 ID
    problem_number = request.data.get('problem_number')
    status = request.data.get('status')

    try:
        problem = Problem.objects.get(problem_number=problem_number)
        # 创建历史记录
        record = RecommendationHistory.create_record(user=request.user, problem=problem, timestamp=timezone.now(),
                                                     status=status)
        # 根据状态处理逻辑
        if status != 'AC':
            # 添加到撤销池，如果不是解决状态
            UserUndoPool.objects.create(user=request.user, problem=problem)
        else:
            # 这里应该调用任务更新函数，并将任务并行执行，现在只对SolvedProblem更新测试
            # SolvedProblem.add_solved_problem(request.user.id, problem.problem_number)
            DataUpdater.update_data_normal(user_id, [problem])
        return JsonResponse({'message': 'Record created successfully'})
    except Problem.DoesNotExist:
        return JsonResponse({'error': 'Problem not found'}, status=404)
    except ValueError as e:
        return JsonResponse({'error': str(e)}, status=400)

@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def init_state_machine(request):
    user_id = request.user.id  # 获取已认证用户的 ID
    try:
        # 尝试创建或获取 RecommendationStateMachine 实例
        instance, created = RecommendationStateMachine.create_or_get_instance(user_id)
        if created:
            message = 'Recommendation state machine created successfully.'
        else:
            message = 'Recommendation state machine retrieved successfully.'

        RecommendationStateMachine.update_task(user_id)

        return JsonResponse({
            'message': message,
            'state_machine_details': {
                'state': instance.state,
                'max_score_problem': instance.max_score_problem.problem_number if instance.max_score_problem else None,
                'second_max_score_problem': instance.second_max_score_problem.problem_number if instance.second_max_score_problem else None
            }
        }, status=200)
    except Exception as e:
        # 处理可能发生的任何异常并返回错误信息
        return JsonResponse({'error': str(e)}, status=500)
@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def delete_state_machine(request):
    user_id = request.user.id  # 获取已认证用户的 ID
    try:
        # 尝试获取并删除 RecommendationStateMachine 实例
        instance = RecommendationStateMachine.objects.get(user_id=user_id)
        instance.delete()  # 删除实例
        return JsonResponse({'message': 'Recommendation state machine deleted successfully'}, status=200)
    except RecommendationStateMachine.DoesNotExist:
        # 如果状态机实例不存在
        return JsonResponse({'error': 'No recommendation state machine found for this user'}, status=404)
    except Exception as e:
        # 处理可能发生的任何其他异常并返回错误信息
        return JsonResponse({'error': str(e)}, status=500)

# 开发测试使用
@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def initialize_recommendation_pool(request):
    user_id = request.user.id  # 获取已认证用户的 ID
    try:
        # 调用类方法以初始化或更新用户的推荐池
        result_message = UserRecommendationPool.init_user_recommendation_pool(user_id)
        return JsonResponse({'message': result_message}, status=200)
    except Exception as e:
        # 处理可能发生的任何异常并返回错误信息
        return JsonResponse({'error': str(e)}, status=500)


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def get_current_recommendation_view(request):
    user = request.user
    problem, message = RecommendationPoolQueue.get_current_recommendation(user.id)

    if problem:
        # 使用序列化器处理问题数据
        serializer = ProblemSerializer(problem)
        return Response({'problem': serializer.data, 'message': message}, status=status.HTTP_200_OK)
    else:
        return Response({'error': message}, status=status.HTTP_404_NOT_FOUND)


# 处理响应
@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def handle_problem_response_view(request):
    user = request.user
    status = request.data.get('status')

    # 验证状态是否提供
    if not status:
        return JsonResponse({'error': 'Status is required.'}, status=400)

    success, message = RecommendationPoolQueue.handle_response(user.id, status)

    if success:
        return JsonResponse({'message': message}, status=200)
    else:
        return JsonResponse({'error': message}, status=400)